<template>
	<view>
		<view class="photo">
			<u-upload :previewFullImage="true" width="250" height="250" :fileList="fileList1" @afterRead="afterRead"
				@delete="deletePic" name="1" multiple :maxCount="1"></u-upload>
		</view>
		<view class="button" @click="tijiao">提交</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList1: [],
				imgurl: '',
				orderid: ''
			};
		},
		onLoad(e) {
			this.orderid = e.orderid;
		},
		methods: {
			tijiao() {
				this.https('/order/punchIn', { clockimg: this.imgurl, orderid: this.orderid }).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					});
					setTimeout(e => {
						uni.navigateBack();
					}, 3000);
				});
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map(item => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://sanju.xinyunweb.com/api/newupload/postImage',
						// url: 'https://chazhichashi.rchz.top/api/newupload/postImage', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: res => {
							setTimeout(() => {
								resolve(res.data.data);
								let data = JSON.parse(res.data);
								this.imgurl = data.data;
							}, 1000);
						}
					});
				});
			}
		}
	};
</script>

<style lang="scss">
	.photo {
		width: 500rpx;
		margin: 200rpx auto 0;
	}

	.u-upload__button--hover {
		margin: 0;
	}

	.button {
		width: 90%;
		position: absolute;
		bottom: 32rpx;
		text-align: center;
		color: #fff;
		left: 5%;
		border-radius: 16rpx;
		padding: 32rpx 0;
		background-color: #45bb52;
	}
</style>